package com.gali.lovefinder.factory.message;

import com.gali.lovefinder.common.ErrorCode;
import com.gali.lovefinder.constant.RedisConstant;
import com.gali.lovefinder.constant.UserConstant;
import com.gali.lovefinder.exception.BusinessException;
import com.gali.lovefinder.utils.GsonUtil;
import com.gali.lovefinder.utils.VerCodeGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * EmailMessageHandler:
 * 邮箱发送信息
 *
 * @author gali
 * @date 2023/07/06
 */
@Service
@Slf4j
public class EmailMessageHandler extends MessageHandler {
    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void sendMessage(String channel) {
        try {
            //1.创建邮件处理器
            SimpleMailMessage message = new SimpleMailMessage();

            //2.设置发件人信息
            message.setFrom(UserConstant.EMAIL_DEFAULT_ADDRESS);
            message.setTo(channel);
            message.setSubject("欢迎您来到咖喱雨恋");

            //3.生成六位随机验证码
            String code = VerCodeGenerateUtil.generateVerCode();

            //4.将验证码放在redis中（string，hash，set）

            //判断该email是否在redis中
            Boolean isExist = redisTemplate.hasKey(String.format(RedisConstant.REDIS_KEY_EMAIL_MESSAGE, channel));

            if (Boolean.TRUE.equals(isExist)) {
                log.error("email exists,this email:{}", GsonUtil.toJson(channel));
                throw new BusinessException(ErrorCode.MESSAGE_CODE_EXISTS);
            }
            redisTemplate.opsForValue().set(String.format(RedisConstant.REDIS_KEY_EMAIL_MESSAGE, channel), GsonUtil.toJson(code));
            redisTemplate.expire(String.format(RedisConstant.REDIS_KEY_EMAIL_MESSAGE, channel), 5, TimeUnit.MINUTES);

            //5.发送信息
            message.setText("亲爱的用户,您好:\n"
                    + "\n本次的邮件验证码为:" + code + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                    + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）\n"
                    + "\n 欢迎各位大佬点个star♥！！");
            javaMailSender.send(message);
        } catch (Exception e) {
            log.error("Error sending message");
            throw new BusinessException(ErrorCode.MESSAGE_SEND_ERROR);
        }

    }
}
